package com.cooldatasoft.menu;

import java.util.ArrayList;
import java.util.List;

import org.apache.wicket.AttributeModifier;
import org.apache.wicket.Page;
import org.apache.wicket.ResourceReference;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.markup.html.AjaxLink;
import org.apache.wicket.extensions.ajax.markup.html.modal.ModalWindow;
import org.apache.wicket.markup.html.IHeaderContributor;
import org.apache.wicket.markup.html.IHeaderResponse;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.link.IPageLink;
import org.apache.wicket.markup.html.link.PageLink;
import org.apache.wicket.markup.html.list.ListItem;
import org.apache.wicket.markup.html.list.ListView;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.markup.html.resources.CompressedResourceReference;
import org.apache.wicket.model.Model;

import com.cooldatasoft.app.WOCApplication;
import com.cooldatasoft.data.Node;
import com.cooldatasoft.data.Person;
import com.cooldatasoft.menu.modal.AddSubGroupModalPanel;
import com.cooldatasoft.web.cms.main.AdminOrganizationChart;
import com.cooldatasoft.web.product.person.PersonPage;

public class AdminNodeBox extends Panel implements IHeaderContributor{

	private static final String MENU_ADD_SUBGROUP = "Add Subgroup";
	private static final String MENU_ADD_PERSON = "Add Person";
	private static final String MENU_ADD_MANAGER = "Add Manager";
	private static final String MENU_DELETE_GROUP = "Delete Group";
	private static final String MENU_EDIT_GROUP = "Edit Group";
	private ResourceReference SHORTCUTS_JAVASCRIPT;
	private ResourceReference SHORTCUTS_CSS;
	final ModalWindow addSubgroupModal = new ModalWindow("modalAddSubgroup");
	
	
	public AdminNodeBox(String id, final Integer nodeId,Boolean showSubPersonList) {
		super(id);
		
		SHORTCUTS_JAVASCRIPT = new CompressedResourceReference(AdminNodeBox.class,"anylink/anylinkcssmenu.js");
		SHORTCUTS_CSS = new CompressedResourceReference(AdminNodeBox.class,"anylink/anylinkcssmenu.css");
		
		List<String> menuList = new ArrayList<String>();
		menuList.add(MENU_EDIT_GROUP);
		menuList.add(MENU_DELETE_GROUP);
		menuList.add(MENU_ADD_MANAGER);
		menuList.add(MENU_ADD_PERSON);
		menuList.add(MENU_ADD_SUBGROUP);
		
		
		boolean isTreeRoot=false;
		
		final AttributeModifier attributeModifier = new AttributeModifier("target",true,new Model("_blank"));		
		Node rootNode = WOCApplication.get().getNodeServiceProxy().get(nodeId);	
		
		if(rootNode.getId()==1){
			isTreeRoot=true;
		}
//		nodeManagerTitle
		
		//Title of the box
		PageLink departmentNameLink = new PageLink("departmentNameLink", new IPageLink() {
			public Page getPage() {
				return new AdminOrganizationChart(nodeId);
			}
			public Class getPageIdentity() {
				return AdminOrganizationChart.class;
			}
		});
		Label titleLabel = new Label("label",rootNode.getLabel());
		titleLabel.setRenderBodyOnly(true);
		departmentNameLink.add(titleLabel);
		
		
		
		
		//Add new group modal window code
		addSubgroupModal.setOutputMarkupId(true);
		AddSubGroupModalPanel addChildGroupModalPanel = new AddSubGroupModalPanel(addSubgroupModal,nodeId);
		addSubgroupModal.setContent(addChildGroupModalPanel);
		addSubgroupModal.setTitle("Add New Group Modal");
		addSubgroupModal.setCookieName("addChildGroupModal");
		addSubgroupModal.setInitialWidth(200);
		addSubgroupModal.setInitialHeight(200);
		addSubgroupModal.setResizable(false);
		addSubgroupModal.setWidthUnit("px");
		addSubgroupModal.setHeightUnit("px"); 
        
        

		addSubgroupModal.setCloseButtonCallback(new ModalWindow.CloseButtonCallback(){
            public boolean onCloseButtonClicked(AjaxRequestTarget target){
                return true;
            }
        });

		addSubgroupModal.setWindowClosedCallback(new ModalWindow.WindowClosedCallback(){
            public void onClose(AjaxRequestTarget target){
            	//refresh main page after adding new group/department
            	setResponsePage(new AdminOrganizationChart(nodeId));
            }
        });
		add(addSubgroupModal);
		
		
		/**
		 * For CMS to show the Root node below if stament executes and creates a ROOT node on the page.
		 */
		if(isTreeRoot){
			PageLink nodeManagerLink = new PageLink("nodeManagerLink", new IPageLink() {
				public Page getPage() {
					return null;
				}
				public Class getPageIdentity() {
					return PersonPage.class;
				}
			});
			nodeManagerLink.add(new Label("label",""));		
			nodeManagerLink.add(attributeModifier);			
			ListView groupMembers = new ListView("groupMembers", new ArrayList<Person>()) {
			    protected void populateItem(ListItem item) {					
			       PageLink memberLink = new PageLink("memberLink", new IPageLink() {
			    	   public Page getPage() {
			    		   return null;
			    	   }
			    	   public Class getPageIdentity() {
			    		   return PersonPage.class;
			    	   }
			       });
			       memberLink.add(new Label("label","").setRenderBodyOnly(true));
			       memberLink.add(attributeModifier);
			       item.add(memberLink);
			    }
			};
			groupMembers.setOutputMarkupPlaceholderTag(false);

			List<String> rootMenuList = new ArrayList<String>();
			rootMenuList.add("Add Child Group");
			ListView menuListView = new ListView("menuListView", rootMenuList) {
			    protected void populateItem(ListItem item) {
			    	
			    	String menuText = item.getModelObjectAsString();
			    	
			    	AjaxLink memberLink = new AjaxLink("pageLink") {
						@Override
						public void onClick(AjaxRequestTarget target) {
							addSubgroupModal.show(target);						
						}		    		
			    	};
			    	Label menuTextLabel = new Label("menuTextLabel",menuText);
			    	menuTextLabel.setRenderBodyOnly(true);
			    	memberLink.add(menuTextLabel);	    	
			       
			    	item.add(memberLink);
			    }
			};
			
			add(new WebMarkupContainer("line").setRenderBodyOnly(true));
			add(departmentNameLink);
			add(nodeManagerLink);
			add(new Label("nodeManagerTitle",""));
			add(groupMembers);
			add(menuListView);
			
			return;
		}
		
		
		//Manager of the Box
		final Person manager = WOCApplication.get().getPersonServiceProxy().get(rootNode.getManagerId());
		String name = WOCApplication.get().getPersonServiceProxy().getName(manager.getId(),true);
		String surname = WOCApplication.get().getPersonServiceProxy().getSurname(manager.getId(),true);
		String position = WOCApplication.get().getPersonServiceProxy().getPosition(manager.getId(),true);
		
		PageLink nodeManagerLink = new PageLink("nodeManagerLink", new IPageLink() {
			public Page getPage() {
				return new PersonPage(manager.getId());
			}
			public Class getPageIdentity() {
				return PersonPage.class;
			}
		});
		
		Label managerTitle = new Label("nodeManagerTitle",position);
		Label managerNameSurnameLabel = new Label("label",name+" "+surname);
		managerNameSurnameLabel.setRenderBodyOnly(true);
		nodeManagerLink.add(managerNameSurnameLabel);		
		nodeManagerLink.add(attributeModifier);
		
		List<Person> personList = new ArrayList<Person>();
		//Dont show any sub person list for the top root node
		if(showSubPersonList){
			//Retrieve person object connected to this node
			personList = WOCApplication.get().getPersonServiceProxy().getPersonList(rootNode.getManagerId());
			//Find Managers of child nodes
			List<Node> childNodeList = WOCApplication.get().getNodeServiceProxy().getChildrenNodeList(rootNode.getId());
			//Add Child Node managers to person list
			for(Node node:childNodeList){
				Integer childNodeManagerId = node.getManagerId();
				Person childNodeManager = WOCApplication.get().getPersonServiceProxy().get(childNodeManagerId);
				if(!personList.contains(childNodeManager)){
					personList.add(childNodeManager);
				}
			}
			//Remove manager from the list
			for(Person person:personList){
				if(person.getId().equals(manager.getId())){
					personList.remove(person);
					break;
				}
			}
		}	
		
		ListView groupMembers = new ListView("groupMembers", personList) {
		    protected void populateItem(ListItem item) {
		       final Person currentPerson = (Person) item.getModelObject();
		       String name = WOCApplication.get().getPersonServiceProxy().getName(currentPerson.getId(),true);
		       String surname = WOCApplication.get().getPersonServiceProxy().getSurname(currentPerson.getId(),true);
				
		       PageLink memberLink = new PageLink("memberLink", new IPageLink() {
		    	   public Page getPage() {
		    		   return new PersonPage(currentPerson.getId());
		    	   }
		    	   public Class getPageIdentity() {
		    		   return PersonPage.class;
		    	   }
		       });
		       Label memberNameSurnameLabel = new Label("label",name+" "+surname);
		       memberNameSurnameLabel.setRenderBodyOnly(true);
		       memberLink.add(memberNameSurnameLabel);
		       memberLink.add(attributeModifier);
		       
		       item.add(memberLink);
		    }
		};
		groupMembers.setOutputMarkupPlaceholderTag(false);
		
		//Dont render line if there is no person to list in the subperson list.
		//Dont show any sub person list for the top root node
		WebMarkupContainer line = new WebMarkupContainer("line");
		if(personList.size()<1 || !showSubPersonList){
			line.setRenderBodyOnly(true);
		}
		
		
		ListView menuListView = new ListView("menuListView", menuList) {
		    protected void populateItem(ListItem item) {
		    	
		    	final String menuText = item.getModelObjectAsString();
		    	AjaxLink memberLink = new AjaxLink("pageLink") {
					@Override
					public void onClick(AjaxRequestTarget target) {
						if(MENU_ADD_SUBGROUP.equals(menuText)){
							addSubgroupModal.show(target);		
						}
					}		    		
		    	};

		    	Label menuTextLabel = new Label("menuTextLabel",menuText);
		    	menuTextLabel.setRenderBodyOnly(true);
		    	memberLink.add(menuTextLabel);	    	
		       
		    	item.add(memberLink);
		    }
		};
		
		add(line);
		add(departmentNameLink);
		add(nodeManagerLink);
		add(managerTitle);
		add(groupMembers);
		add(menuListView);
	}

	
	public void renderHead(IHeaderResponse response) {
		response.renderJavascriptReference(SHORTCUTS_JAVASCRIPT);
        response.renderCSSReference(SHORTCUTS_CSS);	
	}

}
